const Service = require('egg').Service;

class UsersService extends Service {
    /**
     * @param {提交的数据} data 
     * @return 1，0
     */
    async add(data) {

        return 1;
    }

    /**
     * 获取用户
     * @param {*} query 
     * @param {*} sole 
     */
    async findBySole(query, sole) {
        const { ctx,app } = this;
        //通过用户名/手机号获取用户信息
        sole = sole || "login_name";
        let quarySql = `SELECT t.*,(select GROUP_CONCAT(ur.role_id) FROM sys_user_role ur where ur.user_id=t.user_id) as role_id FROM sys_user t 
        where t.${sole} =:${sole} and t.deleted='0'`;
        let whereParams = {
            [sole]: query
        }
        let users = await ctx.model.query(quarySql,
            { replacements: whereParams, raw: true, type: app.Sequelize.QueryTypes.SELECT });
        return users;
    }

    /**
     * @param {提交的数据} quary 
     * @return 
     */
    async list(query) {
        const { ctx, app } = this;
        let { page, pageSize } = query;
        pageSize = pageSize || 10;
        page = page || 1;
        //查询列表
        let users = await ctx.model.query('SELECT * FROM sys_user u WHERE u.deleted=:deleted LIMIT :offset, :limit',
            { replacements: { deleted: '0', offset: (page - 1) * pageSize, limit: pageSize * 1 }, raw: true, type: app.Sequelize.QueryTypes.SELECT });
        //查询总数
        let count = await ctx.model.query('SELECT count(*) as total FROM sys_user u WHERE u.deleted=:deleted',
            { replacements: { deleted: '0' }, raw: true, type: app.Sequelize.QueryTypes.SELECT });

        return {
            list: users,
            total: count[0].total
        };
    }
}

module.exports = UsersService;